package com.shop.common;

import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Slf4j
@Service("sendMessageUtil")
public class SendMessageUtil {

    @Value("${secretId}")
    private String secretId;

    @Value("${secretKey}")
    private String secretKey;

    @Value("${sDKAppID}")
    private String appid;

    private static final String sign = "靳旺学习测试";

    @Autowired
    private RedisUtil redisUtil;


    /**
     * 单发短信
     *
     * @param param
     * @return
     * @throws Exception
     */
    public SendSmsResponse getCredential(Map<String, Object> otherParam, String... param) throws Exception {
        String code = NoUtil.verificationCode();
        List<String> list = new ArrayList(Arrays.asList(param));
        list.add(0,code);
        param = list.stream().toArray(String[]::new);
        List<Object> phones = new ArrayList<>();
        phones.add(otherParam.get("phone"));
        otherParam.putIfAbsent("phones",phones);
        SendSmsResponse sendSmsResponse = this.sendMessage(otherParam, param);
        redisUtil.set(code, otherParam.get("phone").toString(), Long.valueOf(otherParam.get("time").toString()));
        log.info("redis 中验证码：[{}] 对应的手机号是：[{}]", code, redisUtil.get(code));
        return sendSmsResponse;
    }

    private SendSmsResponse sendMessage(Map<String, Object> otherParam, String... param) throws Exception {
        List<String> phones = BaseUtil.formatMessagePhone(BaseUtil.objToList(otherParam.get("phones")));
        Credential cred = new Credential(secretId, secretKey);
        SmsClient client = new SmsClient(cred, "");
        SendSmsRequest req = new SendSmsRequest();
        req.setSmsSdkAppid(appid);
        req.setSign(sign);
        req.setSenderId("");
        log.info("短信模板id：[{}]", otherParam.get("shortMessageId").toString());
        req.setTemplateID(otherParam.get("shortMessageId").toString());
        if (phones.size() == 0) throw new Exception("发送短信的手机号码为空！");
        String[] phoneNumbers = phones.stream().toArray(String[]::new);
        log.info("发送短信手机号：[{}]", phoneNumbers);
        req.setPhoneNumberSet(phoneNumbers);
        log.info("发送短信参数：[{}]", param);
        req.setTemplateParamSet(param);
        SendSmsResponse res = client.SendSms(req);
        log.info("短信发送结果：[{}]", SendSmsResponse.toJsonString(res));
        return res;
    }

}
